package com.ptswitch.material.pages.security;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.ActivationRequestParameter;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.project.SplitPageInfo;
import org.hxzon.tapestry5.util.TapestryEx;

import com.ptswitch.material.model.common.EMailAddress;
import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.EMailAddressService;
import com.ptswitch.material.service.UserService;
import com.ptswitch.material.util.security.PermissionUtil;

public class ListUser extends PageBase {
    @Inject
    private UserService userSer;
    @Inject
    private EMailAddressService emailAddressSer;
    //
    @Property
    private SplitPageInfo userPage;
    @ActivationRequestParameter
    @Property
    private String username;
    @Property
    private List<Uzer> list;
    @Property
    private List<EMailAddress> emailAddresses;
    @Property
    private EMailAddress emailAddress;

    @OnEvent(value = EventConstants.ACTIVATE)
    void init() {
        checkPermitted(PermissionUtil.UserList);
        userPage = new SplitPageInfo();
        userPage.setPageSize(10);
        emailAddress = new EMailAddress();
    }

    @SetupRender
    void display() {
        prepareUser();
        emailAddresses = emailAddressSer.findAll();
    }

    private void prepareUser() {
        username = (username == null) ? "" : username;
        userPage.setRowCount(userSer.countLikeByUsername(username));
        list = userSer.likeByUsername(username, userPage.getCurrentRow(), userPage.getPageSize());
    }

    @OnEvent(value = TapestryEx.Event_BeforeGridInplaceUpdate)
    void changeUserPage() {
        prepareUser();
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "search")
    Object search() {
        return this;
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "addAddress")
    Object addAddress() {
        checkPermitted(PermissionUtil.EmailAddressAll);
        emailAddressSer.save(emailAddress);
        return null;
    }

}
